// 主应用逻辑
document.addEventListener('DOMContentLoaded', async () => {
  // DOM 元素
  const navLinks = document.querySelectorAll('.nav-link');
  const navbarBrand = document.querySelector('.navbar-brand');
  const searchInput = document.getElementById('search-input');
  const searchBtn = document.querySelector('.search-btn');
  const clearSearchBtn = document.querySelector('.clear-search-btn');
  const addWordBtn = document.getElementById('add-btn');
  const wordModal = document.getElementById('word-modal');
  const modalTitle = document.getElementById('modal-title');
  const closeBtn = document.querySelector('.close-btn');
  const cancelBtn = document.querySelector('.cancel-btn');
  const wordForm = document.querySelector('.word-form');
  const wordInput = document.getElementById('word');
  const pronunciationInput = document.getElementById('pronunciation');
  const translationInput = document.getElementById('translation');
  const exampleInput = document.getElementById('example');
  const wordList = document.getElementById('word-list');
  const emptyMessage = document.querySelector('.empty-message');
  const filterBtns = document.querySelectorAll('.filter-btn');
  
  // 管理功能相关元素
  const manageBtn = document.getElementById('manage-btn');
  const manageActions = document.getElementById('manage-actions');
  const deleteSelectedBtn = document.getElementById('delete-selected-btn');
  const finishManageBtn = document.getElementById('finish-manage-btn');
  const selectAllCheckbox = document.getElementById('select-all-checkbox');
  
  // 视图切换相关元素
  const switchViewBtn = document.getElementById('switch-view-btn');
  const wordTable = document.getElementById('word-table');
  const wordCardList = document.getElementById('word-card-list');
  
  // 分页相关元素
  const firstPageBtn = document.getElementById('first-page');
  const prevPageBtn = document.getElementById('prev-page');
  const nextPageBtn = document.getElementById('next-page');
  const lastPageBtn = document.getElementById('last-page');
  const pageNumbers = document.getElementById('page-numbers');
  const jumpPageInput = document.getElementById('jump-page');
  const jumpBtn = document.getElementById('jump-btn');
  const pageInfoText = document.getElementById('page-info-text');
  
  let currentEditId = null;
  let currentFilter = 'newest'; // 默认按最新排序
  let currentPage = 1;
  const itemsPerPage = 10;
  
  // 视图状态管理
  let isCardView = false; // 默认表格视图
  
  // 登录状态管理
  let isLoggedIn = false; // 默认未登录状态
  
  /**
   * 检查用户是否已登录
   * @returns {boolean} 返回登录状态
   */
  const checkLoginStatus = () => {
    try {
      // 优先检查localStorage（记住登录状态）
      let userStr = localStorage.getItem('user');
      let isLoggedIn = localStorage.getItem('isLoggedIn');
      
      // 如果localStorage中没有，检查sessionStorage（临时登录）
      if (!userStr || isLoggedIn !== 'true') {
        userStr = sessionStorage.getItem('user');
        isLoggedIn = sessionStorage.getItem('isLoggedIn');
      }
      
      return userStr && isLoggedIn === 'true';
    } catch (error) {
      // console.error('Failed to check login status:', error);
      return false;
    }
  };
  
  /**
   * 获取当前用户信息
   * @returns {Object|null} 返回用户信息或null
   */
  const getCurrentUser = () => {
    try {
      // 优先从localStorage获取用户信息
      let userStr = localStorage.getItem('user');
      
      // 如果localStorage中没有，从sessionStorage获取
      if (!userStr) {
        userStr = sessionStorage.getItem('user');
      }
      
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      // console.error('Failed to parse user data:', error);
      return null;
    }
  };
  
  /**
   * 更新导航栏用户显示
   */
  const updateNavbarUserDisplay = () => {
    const navLogin = document.getElementById('nav-login');
    const userDropdown = document.getElementById('user-dropdown');
    const navUsername = document.getElementById('nav-username');
    const navUserAvatar = document.getElementById('nav-user-avatar');
    
    if (checkLoginStatus()) {
      const user = getCurrentUser();
      if (user && navLogin && userDropdown && navUsername) {
        navLogin.style.display = 'none';
        userDropdown.style.display = 'block';
        navUsername.textContent = user.nickname;
        
        // 设置导航栏头像
        if (navUserAvatar) {
          if (user.avatar && user.avatar !== 'img/default-avatar.png') {
            // 如果是上传的头像，添加时间戳防止缓存
            let avatarUrl = user.avatar;
            
            // 确保路径正确处理，兼容不同的部署环境
            if (avatarUrl.startsWith('img/')) {
              // 相对路径，直接使用
              avatarUrl = avatarUrl;
            }
            
            const finalAvatarUrl = `${avatarUrl}?t=${Date.now()}`;
            
            navUserAvatar.src = finalAvatarUrl;
            
            // 添加错误处理，如果头像加载失败则使用默认头像
            navUserAvatar.onerror = () => {
              console.warn('⚠️ 头像加载失败，使用默认头像:', avatarUrl);
              navUserAvatar.src = 'img/default-avatar.png';
              navUserAvatar.onerror = null; // 防止无限循环
            };
          } else {
              navUserAvatar.src = 'img/default-avatar.png';
            }
        }
      }
    } else {
      if (navLogin && userDropdown) {
        navLogin.style.display = 'block';
        userDropdown.style.display = 'none';
      }
    }
  };
  
  /**
   * 用户登出
   */
  const logout = () => {
    // 清除localStorage中的登录信息
    localStorage.removeItem('user');
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('rememberLogin');
    
    // 清除sessionStorage中的登录信息
    sessionStorage.removeItem('user');
    sessionStorage.removeItem('isLoggedIn');
    
    updateNavbarUserDisplay();
    
    // 跳转到登录页面
    window.location.href = 'pages/account.html';
  };
  
  /**
   * 显示登录提示对话框
   * @param {string} action - 操作名称
   */
  const showLoginPrompt = (action = '操作') => {
    showActionDialog(
      '需要登录',
      `登录后才能进行${action}`,
      {
        actionText: '登录',
        actionType: 'primary',
        onAction: () => {
          window.location.href = 'pages/account.html';
        },
        onCancel: () => {
          // 取消操作，什么都不做
        }
      }
    );
  };
  
  /**
   * 权限检查装饰器
   * @param {Function} callback - 需要权限的回调函数
   * @param {string} action - 操作名称
   * @returns {Function} 包装后的函数
   */
  const requireLogin = (callback, action = '操作') => {
    return (...args) => {
      if (!checkLoginStatus()) {
        showLoginPrompt(action);
        return;
      }
      return callback(...args);
    };
  };
  
  // 初始化数据
  try {
    await WordData.initializeData();
    // console.log('Data initialized successfully');
  } catch (error) {
    // console.error('Failed to initialize data:', error);
  }
  
  /**
   * 初始化应用
   */
  const initApp = async () => {
    setupEventListeners();
    updateNavbarUserDisplay();
    
    // 根据窗口宽度自动选择视图模式
    checkAndSetInitialView();
    
    await renderWordList();
  };
  
  /**
   * 检测窗口宽度并设置初始视图
   */
  const checkAndSetInitialView = () => {
    const windowWidth = window.innerWidth;
    
    if (windowWidth <= 720) {
      // 小屏幕：切换到卡片视图
      if (!isCardView) {
        isCardView = true;
        wordTable.style.display = 'none';
        wordCardList.style.display = 'block';
        switchViewBtn.innerHTML = '<img src="img/icon-cards.svg" alt="切换视图" width="16" height="16">';
      }
    } else {
      // 大屏幕：保持表格视图
      if (isCardView) {
        isCardView = false;
        wordTable.style.display = 'table';
        wordCardList.style.display = 'none';
        switchViewBtn.innerHTML = '<img src="img/icon-table.svg" alt="切换视图" width="16" height="16">';
      }
    }
  };
  
  /**
   * 切换视图
   */
  const toggleView = () => {
    isCardView = !isCardView;
    
    if (isCardView) {
      // 切换到卡片视图
      wordTable.style.display = 'none';
      wordCardList.style.display = 'block';
      switchViewBtn.innerHTML = '<img src="img/icon-cards.svg" alt="切换视图" width="16" height="16">';
    } else {
      // 切换到表格视图
      wordTable.style.display = 'table';
      wordCardList.style.display = 'none';
      switchViewBtn.innerHTML = '<img src="img/icon-table.svg" alt="切换视图" width="16" height="16">';
    }
    
    // 重新渲染当前视图
    renderWordList();
  };
  
  /**
   * 筛选和排序单词
   * @param {string} filter - 筛选条件 ('memorized', 'unmemorized', 'oldest', 'newest')
   * @returns {Promise<Array>} 返回筛选和排序后的单词数组
   */
  const filterAndSortWords = async (filter = currentFilter) => {
    let words = WordData.getAllWords();
    
    // 如果缓存为空，尝试刷新
    if (!words || words.length === 0) {
      try {
        words = await WordData.refreshCache();
      } catch (error) {
        // console.error('Failed to refresh data:', error);
        words = [];
      }
    }
    
    // 创建副本避免修改原数组
    words = [...words];
    
    // 根据筛选条件过滤和排序
    switch (filter) {
      case 'memorized':
        words = words.filter(word => word.memorized === true);
        break;
      case 'unmemorized':
        words = words.filter(word => word.memorized === false);
        break;
      case 'oldest':
        words = words.sort((a, b) => {
          const dateA = new Date(a.createDate);
          const dateB = new Date(b.createDate);
          return dateA - dateB;
        });
        break;
      case 'newest':
      default:
        words = words.sort((a, b) => {
          const dateA = new Date(a.createDate);
          const dateB = new Date(b.createDate);
          return dateB - dateA;
        });
        break;
    }
    
    return words;
  };
  
  /**
   * 对给定的单词数组应用当前筛选
   * @param {Array} words - 单词数组
   * @returns {Array} 返回筛选后的单词数组
   */
  const applyCurrentFilter = (words) => {
    // 创建副本避免修改原数组
    const wordsCopy = [...words];
    
    switch (currentFilter) {
      case 'memorized':
        return wordsCopy.filter(word => word.memorized === true);
      case 'unmemorized':
        return wordsCopy.filter(word => word.memorized === false);
      case 'oldest':
        return wordsCopy.sort((a, b) => {
          const dateA = new Date(a.createDate);
          const dateB = new Date(b.createDate);
          return dateA - dateB;
        });
      case 'newest':
      default:
        return wordsCopy.sort((a, b) => {
            const dateA = new Date(a.createDate);
            const dateB = new Date(b.createDate);
            return dateB - dateA;
          });
    }
  };
  
  /**
   * 渲染单词列表
   * @param {Array|null} words - 要渲染的单词数组，为null时使用筛选后的所有单词
   */
  const renderWordList = async (words = null) => {
    const allWords = words || await filterAndSortWords();
    const totalPages = Math.ceil(allWords.length / itemsPerPage);
    
    // 更新单词统计信息
    updateWordStatistics(allWords);
    
    // 确保当前页码在有效范围内
    if (currentPage > totalPages && totalPages > 0) {
      currentPage = totalPages;
    } else if (currentPage < 1) {
      currentPage = 1;
    }
    
    // 计算当前页的数据
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const wordsToRender = allWords.slice(startIndex, endIndex);
    
    if (allWords.length === 0) {
      wordList.innerHTML = '';
      wordCardList.innerHTML = '';
      emptyMessage.classList.remove('hidden');
      document.querySelector('.pagination-container').style.display = 'none';
      return;
    }
    
    emptyMessage.classList.add('hidden');
    document.querySelector('.pagination-container').style.display = 'flex';
    
    if (isCardView) {
      // 渲染卡片视图
      renderCardView(wordsToRender, startIndex);
    } else {
      // 渲染表格视图
      renderTableView(wordsToRender, startIndex);
    }
    
    // 渲染分页器
    renderPagination(totalPages, allWords.length);
  };
  
  /**
   * 更新单词统计信息
   * @param {Array} words - 单词数组
   */
  const updateWordStatistics = (words) => {
    const totalWords = words.length;
    const rememberedWords = words.filter(word => word.memorized === true).length;
    const unrememberedWords = totalWords - rememberedWords;
    
    const statisticsElement = document.getElementById('word-count-statistics');
    if (statisticsElement) {
      statisticsElement.textContent = `共 ${totalWords} 个单词，未记住 ${unrememberedWords} 个，已记住 ${rememberedWords} 个`;
    }
  };
  
  // 渲染表格视图
  const renderTableView = (wordsToRender, startIndex) => {
    wordList.innerHTML = wordsToRender.map((word, index) => {
      const serialNumber = String(startIndex + index + 1).padStart(5, '0');
      return `
        <tr class="${word.memorized ? 'memorized' : ''}" data-id="${word.id}">
          <td class="checkbox-column" style="display: none;">
            <input type="checkbox" class="word-checkbox" />
          </td>
          <td>${serialNumber}</td>
          <td>${word.word}</td>
          <td>/${word.pronunciation}/</td>
          <td>${word.translation.replace(/\n/g, '<br>')}</td>
          <td>${word.example.replace(/\n/g, '<br>')}</td>
          <td>
            <div class="actions">
              <button class="edit-btn" title="编辑">
                <img src="img/edit.svg" alt="编辑" class="action-icon">
              </button>
              <button class="delete-btn" title="删除">
                <img src="img/delete.svg" alt="删除" class="action-icon">
              </button>
              <button class="memorized-btn ${word.memorized ? 'memorized' : 'unmemorized'}">${word.memorized ? '已记住' : '未记住'}</button>
            </div>
          </td>
        </tr>
      `;
    }).join('');
  };
  
  // 渲染卡片视图
  const renderCardView = (wordsToRender, startIndex) => {
    wordCardList.innerHTML = wordsToRender.map((word, index) => {
      const serialNumber = String(startIndex + index + 1).padStart(5, '0');
      return `
        <div class="word-card ${word.memorized ? 'memorized' : ''}" data-id="${word.id}">
          <div class="word-card-number">${serialNumber}</div>
          <input type="checkbox" class="word-card-checkbox word-checkbox" />
          <div class="word-card-content">
            <div class="word-card-main">
              <span class="word-card-word">${word.word}</span>
              <span class="word-card-pronunciation">/${word.pronunciation}/</span>
            </div>
            <div class="word-card-translation">${word.translation}</div>
            <div class="word-card-example">${word.example}</div>
            <div class="word-card-actions">
              <button class="edit-btn" title="编辑">
                <img src="img/edit.svg" alt="编辑" class="action-icon">
              </button>
              <button class="delete-btn" title="删除">
                <img src="img/delete.svg" alt="删除" class="action-icon">
              </button>
              <button class="memorized-btn ${word.memorized ? 'memorized' : 'unmemorized'}">${word.memorized ? '已记住' : '未记住'}</button>
            </div>
          </div>
        </div>
      `;
    }).join('');
  };
  
  // 渲染分页器
  const renderPagination = (totalPages, totalItems) => {
    // 更新页面信息
    pageInfoText.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
    
    // 更新按钮状态
    firstPageBtn.disabled = currentPage === 1;
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages;
    lastPageBtn.disabled = currentPage === totalPages;
    
    // 设置跳转输入框的最大值
    jumpPageInput.max = totalPages;
    
    // 渲染页码按钮
    renderPageNumbers(totalPages);
  };
  
  // 渲染页码按钮
  const renderPageNumbers = (totalPages) => {
    pageNumbers.innerHTML = '';
    
    if (totalPages <= 10) {
      // 总页数不超过10页，显示所有页码
      for (let i = 1; i <= totalPages; i++) {
        const pageBtn = createPageButton(i);
        pageNumbers.appendChild(pageBtn);
      }
    } else {
      // 总页数超过10页，使用省略号
      const startPage = Math.max(1, currentPage - 4);
      const endPage = Math.min(totalPages, currentPage + 4);
      
      // 始终显示第1页
      if (startPage > 1) {
        pageNumbers.appendChild(createPageButton(1));
        if (startPage > 2) {
          pageNumbers.appendChild(createEllipsis());
        }
      }
      
      // 显示当前页附近的页码
      for (let i = startPage; i <= endPage; i++) {
        const pageBtn = createPageButton(i);
        pageNumbers.appendChild(pageBtn);
      }
      
      // 始终显示最后一页
      if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
          pageNumbers.appendChild(createEllipsis());
        }
        pageNumbers.appendChild(createPageButton(totalPages));
      }
    }
  };
  
  /**
   * 创建页码按钮
   * @param {number} pageNum - 页码数字
   * @returns {HTMLElement} 返回创建的按钮元素
   */
  const createPageButton = (pageNum) => {
    const btn = document.createElement('button');
    btn.className = `pagination-btn ${pageNum === currentPage ? 'active' : ''}`;
    btn.textContent = pageNum;
    btn.addEventListener('click', async () => {
      currentPage = pageNum;
      await renderWordList();
    });
    return btn;
  };
  
  /**
   * 创建省略号元素
   * @returns {HTMLElement} 返回创建的省略号元素
   */
  const createEllipsis = () => {
    const span = document.createElement('span');
    span.textContent = '...';
    span.style.padding = '8px 4px';
    span.style.color = '#666';
    return span;
  };
  
   /**
    * 设置事件监听器
    */
    const setupEventListeners = () => {
      // 导航栏事件
      navLinks.forEach(link => {
        link.addEventListener('click', (e) => {
          // 如果是登录链接，允许默认跳转行为
          if (link.id === 'nav-login') {
            return; // 不阻止默认行为，允许正常跳转
          }
          
          e.preventDefault();
          
          // 移除所有active类
          navLinks.forEach(l => l.classList.remove('active'));
          // 给当前链接添加active类
          link.classList.add('active');
          
          // 根据页面类型处理
           const page = link.dataset.page;
           if (page === 'wordlist') {
             // 显示单词列表内容
             document.querySelector('.app-header').style.display = 'block';
             document.querySelector('main').style.display = 'block';
           } else if (page === 'phrases-list') {
             // 跳转到短语列表页面
             window.location.href = 'pages/phrases-list.html';
           } else if (page === 'vocabulary-test') {
             // 跳转到测试页面
             window.location.href = 'pages/vocabulary-test.html';
           } else if (page === 'update-log') {
             // 跳转到更新日志页面
             window.location.href = 'pages/update-log.html';
           } else {
             // 其他页面暂时显示提示信息
             alert(`${link.textContent}功能正在开发中...`);
           }
        });
       });
       
       // Logo品牌区域点击事件
       navbarBrand.addEventListener('click', (e) => {
         e.preventDefault();
         
         // 移除所有导航链接的active类
         navLinks.forEach(l => l.classList.remove('active'));
         // 激活单词列表导航
         const wordlistNav = document.querySelector('.nav-link[data-page="wordlist"]');
         if (wordlistNav) {
           wordlistNav.classList.add('active');
         }
         
         // 显示单词列表内容
         document.querySelector('.app-header').style.display = 'block';
         document.querySelector('main').style.display = 'block';
       });
       
     // 搜索单词
     searchBtn.addEventListener('click', async () => {
       const query = searchInput.value.trim();
       let results = await WordData.searchWords(query);
       
       // 如果有搜索结果，应用当前筛选
       if (query && results.length > 0) {
         results = applyCurrentFilter(results);
       }
       
       // 重置到第一页
       currentPage = 1;
       
       await renderWordList(results);
       
       // 显示清空搜索按钮
       if (query) {
         clearSearchBtn.classList.remove('hidden');
       }
     });
    
    searchInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        searchBtn.click();
      }
    });
    
    // 清空搜索
    clearSearchBtn.addEventListener('click', async () => {
      searchInput.value = '';
      currentPage = 1;
      await renderWordList();
      clearSearchBtn.classList.add('hidden');
    });
    
    // 筛选按钮事件
     filterBtns.forEach(btn => {
       btn.addEventListener('click', async () => {
         // 移除所有按钮的active类
         filterBtns.forEach(b => b.classList.remove('active'));
         // 给当前按钮添加active类
         btn.classList.add('active');
         
         // 更新当前筛选状态
         currentFilter = btn.dataset.filter;
         
         // 重置到第一页
         currentPage = 1;
         
         // 重新渲染列表
         await renderWordList();
       });
     });
     
     // 分页器事件
     firstPageBtn.addEventListener('click', async () => {
       currentPage = 1;
       await renderWordList();
     });
     
     prevPageBtn.addEventListener('click', async () => {
       if (currentPage > 1) {
         currentPage--;
         await renderWordList();
       }
     });
     
     nextPageBtn.addEventListener('click', async () => {
       const allWords = await filterAndSortWords();
       const totalPages = Math.ceil(allWords.length / itemsPerPage);
       if (currentPage < totalPages) {
         currentPage++;
         await renderWordList();
       }
     });
     
     lastPageBtn.addEventListener('click', async () => {
       const allWords = await filterAndSortWords();
       const totalPages = Math.ceil(allWords.length / itemsPerPage);
       currentPage = totalPages;
       await renderWordList();
     });
     
     jumpBtn.addEventListener('click', async () => {
       const targetPage = parseInt(jumpPageInput.value);
       const allWords = await filterAndSortWords();
       const totalPages = Math.ceil(allWords.length / itemsPerPage);
       if (targetPage >= 1 && targetPage <= totalPages) {
         currentPage = targetPage;
         await renderWordList();
         jumpPageInput.value = '';
       }
     });
     
     jumpPageInput.addEventListener('keypress', (e) => {
       if (e.key === 'Enter') {
         jumpBtn.click();
       }
     });
     
     // 视图切换按钮事件监听器
     if (switchViewBtn) {
       switchViewBtn.addEventListener('click', () => {
         toggleView();
       });
       
       // 添加鼠标悬停提示
       switchViewBtn.addEventListener('mouseenter', () => {
         const tooltipText = isCardView ? '切换为表格视图' : '切换为卡片视图';
         showTooltip(switchViewBtn, tooltipText, 'bottom');
       });
       
       switchViewBtn.addEventListener('mouseleave', () => {
         hideTooltip();
       });
     }
     
     // 管理功能事件监听器
     if (manageBtn) {
       manageBtn.addEventListener('click', requireLogin(() => {
         // 进入管理模式
         manageBtn.style.display = 'none';
         manageActions.style.display = 'flex';
         
         // 为表格添加管理模式类
         const wordTable = document.getElementById('word-table');
         if (wordTable) {
           wordTable.classList.add('manage-mode');
         }
         
         // 隐藏分页器
         const paginationContainer = document.querySelector('.pagination-container');
         if (paginationContainer) {
           paginationContainer.style.display = 'none';
         }
         
         // 隐藏视图切换按钮
         const switchViewBtn = document.getElementById('switch-view-btn');
         if (switchViewBtn) {
           switchViewBtn.style.display = 'none';
         }
         
         // 显示复选框列
         showCheckboxColumn();
       }, '管理单词'));
     }
     
     if (deleteSelectedBtn) {
       deleteSelectedBtn.addEventListener('click', requireLogin(() => {
         deleteSelectedWords();
       }, '删除选中单词'));
     }
     
     if (finishManageBtn) {
       finishManageBtn.addEventListener('click', () => {
         exitManageMode();
       });
      }
      
      // 全选复选框事件
      if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', (e) => {
          const checkboxes = document.querySelectorAll('.word-checkbox');
          checkboxes.forEach(checkbox => {
            checkbox.checked = e.target.checked;
          });
        });
      }
      
     // 登出按钮事件
     const logoutBtn = document.getElementById('logout-btn');
     if (logoutBtn) {
       logoutBtn.addEventListener('click', logout);
     }
      
    // 添加新单词按钮
    addWordBtn.addEventListener('click', requireLogin(() => {
      openAddWordModal();
    }, '添加单词'));
    
    // 单词列表操作（编辑、删除、标记）
    wordList.addEventListener('click', async (e) => {
      const target = e.target;
      const row = target.closest('tr');
      
      if (!row) return;
      
      const id = row.dataset.id;
      
      // 查找实际的按钮元素（处理点击SVG图标的情况）
      const editBtn = target.closest('.edit-btn');
      const deleteBtn = target.closest('.delete-btn');
      const memorizedBtn = target.closest('.memorized-btn');
      
      if (editBtn) {
        requireLogin(async () => {
          await openEditWordModal(id);
        }, '编辑单词')();
      } else if (deleteBtn) {
        requireLogin(async () => {
          showDeleteDialog(
            '确定要删除这个单词吗？此操作不可撤销。',
            async () => {
              try {
                await WordData.deleteWord(id);
                await renderWordList();
                showConfirmDialog('删除成功', '单词已成功删除');
              } catch (error) {
                // console.error('Failed to delete word:', error);
                showConfirmDialog('删除失败', '删除单词失败，请重试');
              }
            }
          );
        }, '删除单词')();
      } else if (memorizedBtn) {
        requireLogin(async () => {
          await WordData.toggleMemorized(id);
          await renderWordList();
        }, '标记单词')();
      }
    });
    
    // 卡片视图操作事件监听器
    wordCardList.addEventListener('click', async (e) => {
      const target = e.target;
      const card = target.closest('.word-card');
      
      if (!card) return;
      
      const id = card.dataset.id;
      
      // 查找实际的按钮元素（处理点击SVG图标的情况）
      const editBtn = target.closest('.edit-btn');
      const deleteBtn = target.closest('.delete-btn');
      const memorizedBtn = target.closest('.memorized-btn');
      
      if (editBtn) {
        requireLogin(async () => {
          await openEditWordModal(id);
        }, '编辑单词')();
      } else if (deleteBtn) {
        requireLogin(async () => {
          showDeleteDialog(
            '确定要删除这个单词吗？此操作不可撤销。',
            async () => {
              try {
                await WordData.deleteWord(id);
                await renderWordList();
                showConfirmDialog('删除成功', '单词已成功删除');
              } catch (error) {
                // console.error('Failed to delete word:', error);
                showConfirmDialog('删除失败', '删除单词失败，请重试');
              }
            }
          );
        }, '删除单词')();
      } else if (memorizedBtn) {
        requireLogin(async () => {
          await WordData.toggleMemorized(id);
          await renderWordList();
        }, '标记单词')();
      }
    });
    
    // 模态框关闭
    closeBtn.addEventListener('click', closeModal);
    cancelBtn.addEventListener('click', closeModal);
    
    // 表单提交
    wordForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      
      const wordData = {
        word: wordInput.value.trim(),
        pronunciation: pronunciationInput.value.trim(),
        translation: translationInput.value.trim(),
        example: exampleInput.value.trim()
      };
      
      try {
        let newWordId = null;
        
        if (currentEditId) {
          // 更新现有单词
          await WordData.updateWord(currentEditId, wordData);
        } else {
          // 添加新单词
          const newWord = await WordData.addWord(wordData);
          newWordId = newWord.id;
        }
        
        await renderWordList();
        closeModal();
        
        // 如果是添加新单词，为新单词行添加高亮动画
        if (newWordId) {
          highlightNewWordRow(newWordId);
        }
      } catch (error) {
        // console.error('Failed to save word:', error);
        alert('保存单词失败，请重试');
      }
    });
  };
  
  /**
   * 打开添加单词模态框
   * @param {string} initialWord - 初始单词值
   */
  const openAddWordModal = (initialWord = '') => {
    modalTitle.textContent = '添加新单词';
    wordForm.reset();
    wordInput.value = initialWord;
    // 设置读音输入框的默认提示
    pronunciationInput.placeholder = '单词发音';
    currentEditId = null;
    wordModal.classList.remove('hidden');
    wordInput.focus();
  };
  
  /**
   * 打开编辑单词模态框
   * @param {string} id - 要编辑的单词ID
   */
  const openEditWordModal = async (id) => {
    try {
      let words = WordData.getAllWords();
      
      // 如果缓存为空，尝试刷新
      if (!words || words.length === 0) {
        words = await WordData.refreshCache();
      }
      
      const word = words.find(w => w.id === id);
      
      if (word) {
        modalTitle.textContent = '编辑单词';
        wordInput.value = word.word;
        pronunciationInput.value = word.pronunciation;
        translationInput.value = word.translation;
        exampleInput.value = word.example;
        // 设置读音输入框的默认提示
        pronunciationInput.placeholder = '单词发音';
        
        currentEditId = id;
        wordModal.classList.remove('hidden');
        wordInput.focus();
      }
    } catch (error) {
      // console.error('Failed to open edit modal:', error);
      alert('打开编辑窗口失败，请重试');
    }
  };
  
  /**
   * 关闭模态框
   */
  const closeModal = () => {
    wordModal.classList.add('hidden');
    wordForm.reset();
    currentEditId = null;
  };
  
  /**
   * 为新添加的单词行添加高亮动画效果
   * @param {string} wordId - 新添加单词的ID
   */
  const highlightNewWordRow = (wordId) => {
    // 使用setTimeout确保DOM已更新
    setTimeout(() => {
      const selector = isCardView ? `.word-card[data-id="${wordId}"]` : `tr[data-id="${wordId}"]`;
      const wordElement = document.querySelector(selector);
      if (wordElement) {
        // 添加高亮动画类
        wordElement.classList.add('new-word-highlight');
        
        // 0.6秒后自动移除动画类
        setTimeout(() => {
          wordElement.classList.remove('new-word-highlight');
        }, 600);
      }
    }, 100);
  };
  
  /**
   * 显示复选框列
   */
  const showCheckboxColumn = () => {
    // 表格视图的复选框列
    const checkboxColumns = document.querySelectorAll('.checkbox-column');
    checkboxColumns.forEach(col => {
      col.style.display = 'table-cell';
    });
    
    // 卡片视图的复选框
    const cardCheckboxes = document.querySelectorAll('.word-card-checkbox');
    cardCheckboxes.forEach(checkbox => {
      checkbox.classList.add('show');
    });
  };
  
  /**
   * 隐藏复选框列
   */
  const hideCheckboxColumn = () => {
    // 表格视图的复选框列
    const checkboxColumns = document.querySelectorAll('.checkbox-column');
    checkboxColumns.forEach(col => {
      col.style.display = 'none';
    });
    
    // 卡片视图的复选框
    const cardCheckboxes = document.querySelectorAll('.word-card-checkbox');
    cardCheckboxes.forEach(checkbox => {
      checkbox.classList.remove('show');
    });
    
    // 清除所有选中状态
    const checkboxes = document.querySelectorAll('.word-checkbox');
    checkboxes.forEach(checkbox => {
      checkbox.checked = false;
    });
  };
  
  /**
   * 删除选中的单词
   */
  const deleteSelectedWords = async () => {
    const selectedCheckboxes = document.querySelectorAll('.word-checkbox:checked');
    
    if (selectedCheckboxes.length === 0) {
      showConfirmDialog('提示', '请先选择要删除的单词');
      return;
    }
    
    const selectedIds = Array.from(selectedCheckboxes).map(checkbox => {
      // 处理表格视图和卡片视图的不同结构
      const tableRow = checkbox.closest('tr');
      const cardElement = checkbox.closest('.word-card');
      
      if (tableRow) {
        return tableRow.dataset.id;
      } else if (cardElement) {
        return cardElement.dataset.id;
      }
      return null;
    }).filter(id => id !== null);
    
    showDeleteDialog(
      `确定要删除选中的 ${selectedIds.length} 个单词吗？此操作不可撤销。`,
      async () => {
        try {
          // 批量删除单词
          for (const id of selectedIds) {
            await WordData.deleteWord(id);
          }
          
          // 退出管理模式
          exitManageMode();
          
          await renderWordList();
          showConfirmDialog('成功', `已成功删除 ${selectedIds.length} 个单词`);
        } catch (error) {
          // console.error('Failed to delete selected words:', error);
          showConfirmDialog('错误', '删除单词失败，请重试');
        }
      }
    );
  };
  
  /**
   * 退出管理模式
   */
  const exitManageMode = () => {
    // 恢复管理按钮显示
    manageBtn.style.display = 'block';
    manageActions.style.display = 'none';
    
    // 移除表格管理模式类
    const wordTable = document.getElementById('word-table');
    if (wordTable) {
      wordTable.classList.remove('manage-mode');
    }
    
    // 恢复分页器显示
    const paginationContainer = document.querySelector('.pagination-container');
    if (paginationContainer) {
      paginationContainer.style.display = 'flex';
    }
    
    // 恢复视图切换按钮显示
    const switchViewBtn = document.getElementById('switch-view-btn');
    if (switchViewBtn) {
      switchViewBtn.style.display = 'block';
    }
    
    // 隐藏复选框列
    hideCheckboxColumn();
  };
  
  // 初始化应用
  await initApp();
});